antd Upload + form-data上传文件

使用Ant Design Upload组件,实现文件随表单一起提交

拦截文件上传

方法1:beforeUpload拦截

1
2
3
4
5
6
7
<Upload
// ...
beforeUpload={beforeUpload}
fileList={fileList}
>
<Button>上传文件</Button>
</Upload>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const beforeUpload =
(file) =>
new Promise((resolve, reject) => {
const {type: fileType, name} = file
// 文件类型与大小判断
if (!isOk) {
// ...
reject(file)
return
}
// 保存fileList,拦截文件上传
setFileList([file])
reject(file)
})

方法2:customRequest拦截

1
2
3
4
5
6
7
8
<Upload
// ...
beforeUpload={beforeUpload}
fileList={fileList}
customRequest: () => {}
>
<Button>上传文件</Button>
</Upload>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const beforeUpload =
(file) =>
new Promise((resolve, reject) => {
const {type: fileType, name} = file
// 文件类型与大小判断
if (!isOk) {
// ...
reject(file)
return
}
// 保存fileList
setFileList([file])
resolve(file)
})

formData 上传文件

1
2
3
4
5
6
7
8
9
10
11
12
// 注意不要手动设置请求头 Content-Type:multipart/form-data
// 注意antd选择后的fileList是经过包装的数据,添加到formData时需要取originFileObj
const submit = () => {
if (fileList.length) {
const formData = new FormData()
// originFileObj:获取原File
const file = fileList[0].originFileObj
formData.append('参数名', file)
formData.append('xxx', xxx) // 其他参数
// request body: formData
}
}